goog.require('goog.dom');
goog.require('goog.dom.forms');
goog.require('goog.string');
goog.require('goog.string.format');
goog.require('goog.format.EmailAddress');
goog.require('goog.asserts');


var INPUT_WARNING_CLASS = 'INPUT_WARNING';
var INVALID_EMAIL_MSG = 'Please enter a valid email address';

function debugPrint(msg) {
    var newHeader = goog.dom.createDom('h1', {'style': 'background-color:#EEE'},
        msg);
      goog.dom.appendChild(document.body, newHeader);
}

function createInputWarning(fieldId, msg) {
  var inputDiv = goog.dom.$(fieldId);
  var warningSpan = goog.dom.createDom('span', {'class': INPUT_WARNING_CLASS}, msg);
  goog.dom.appendChild(inputDiv, warningSpan);
}

function removeAllInputWarning() {
  var elements = goog.dom.getElementsByClass(INPUT_WARNING_CLASS); 
  for (var i = 0; i < elements.length; i++) {
    var element = elements.item(i);
    goog.asserts.assertElement(element);
    goog.dom.removeNode(element);
  }
}

function submitForm() {
  removeAllInputWarning();

  var form = goog.dom.$('mainForm') 
  var email = goog.dom.forms.getValueByName(form, 'email');
  var targetEmail = goog.dom.forms.getValueByName(form, 'targetEmail');
  var content = goog.dom.forms.getValueByName(form, 'content');
  var credential = goog.dom.forms.getValueByName(form, 'credential');

  email = new goog.format.EmailAddress(email);
  var failed = false;
  if (!email.isValid()) {
    createInputWarning('emailInput', INVALID_EMAIL_MSG); 
    failed = true;
  }
  targetEmail = new goog.format.EmailAddress(targetEmail);
  if (!targetEmail.isValid()) {
    createInputWarning('targetEmailInput', INVALID_EMAIL_MSG); 
    failed = true;
  }
  if (goog.string.isEmpty(content)) {
    createInputWarning('contentInput', "Please enter some content."); 
    failed = true;
  }
  if (goog.string.isEmpty(credential)) {
    createInputWarning('credentialInput', "Please enter a crdential."); 
    failed = true;
  }
  debugPrint(goog.string.format(
      '[email:%s][target:%s][content:%s][credential:%s]', 
      email, targetEmail, content, credential))
  if (!failed) {
    form.submit();
  }
}
